package com.copyurl.util;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.FileSystemResource;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class PropertiesUtil {

    public static String getPropertyValue(Project project, String file, String key) {
        Properties properties = getProperty(project, file);
        return properties.getProperty(key) != null ? properties.getProperty(key) : "";
    }

    public static Properties getProperty(Project project, String file) {
        List<VirtualFile> virtualFileList = new ArrayList<>(FilenameIndex.getVirtualFilesByName(file, GlobalSearchScope.allScope(project)));
        if (CollectionUtils.isNotEmpty(virtualFileList)) {
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new FileSystemResource(virtualFileList.get(0).getPath()));
            return yaml.getObject();
        }
        return new Properties();
    }
}
